package dahuiji.common.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import dahuiji.regist.servlet.RegistServlet;

/**
 * Servlet implementation class BaceServlet
 */
public abstract class BaceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger log = Logger.getLogger(RegistServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BaceServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		defaultProc(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		defaultProc(request, response);
	}
	/**
	 * 默认的处理方法
	 * @param request
	 * @param response
	 */
	public void defaultProc(HttpServletRequest request,
			HttpServletResponse response) {
		StringBuffer methodName, param;
		String returnPage = null;
		String backPage = null;

		try {
			returnPage = perform(request, response);
		}catch (java.sql.SQLException e) {
            //DB exception occurs
            System.out.println("SQL Exception:" + e.getMessage());
            request.setAttribute("_error", "SYSTEM_ERROR");
            forwardURL(request, response, returnPage, backPage);
       } catch (Exception e) {
            //Unknown exception occurs
    	   log.warn("-------------异常--------------------");
            System.out.println("\nException:" + e.getMessage() );
            e.printStackTrace( System.out );
            returnPage="/error/404.html";
            request.setAttribute("_error", "SYSTEM_ERROR");
            forwardURL(request, response, returnPage, backPage);
       } finally {
           

       }
       System.out.println("--return page:" + returnPage + " --");

	}
	/**
	 * 子类实现这个方法
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public abstract String perform(HttpServletRequest request,
			HttpServletResponse response) throws Exception;
	/**
	 * 跳转
	 * @param request
	 * @param response
	 * @param returnPage
	 * @param backPage
	 */
	private final void forwardURL(HttpServletRequest request,
			HttpServletResponse response, String returnPage, String backPage) {

		if (backPage != null)
			request.setAttribute("_backPage", backPage);
		try {
			getServletConfig().getServletContext()
					.getRequestDispatcher(returnPage)
					.forward(request, response);
		} catch (Exception e) {
			System.out.println("ReDirector Error:" + e.getMessage());
		}

	}
}
